API CALL

  • Screen 1

    pubspec.yaml

    
    
                  dio: ^5.4.3+1
    
    

    main.dart

    
    
    import 'package:flutter/material.dart';
    import 'package:b/dio_home_screen.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
    
          home: DioHomePage(),
          debugShowCheckedModeBanner: false,
        );
      }
    }
    
    

    dio_model.dart

    
    
    class Cart {
      List<Carts>? carts;
      int? total;
      int? skip;
      int? limit;
    
      Cart({this.carts, this.total, this.skip, this.limit});
    
      Cart.fromJson(Map<String, dynamic> json) {
        if (json['carts'] != null) {
          carts = <Carts>[];
          json['carts'].forEach((v) {
            carts!.add(new Carts.fromJson(v));
          });
        }
        total = json['total'];
        skip = json['skip'];
        limit = json['limit'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        if (this.carts != null) {
          data['carts'] = this.carts!.map((v) => v.toJson()).toList();
        }
        data['total'] = this.total;
        data['skip'] = this.skip;
        data['limit'] = this.limit;
        return data;
      }
    }
    
    class Carts {
      int? id;
      List<Products>? products;
      int? total;
      int? discountedTotal;
      int? userId;
      int? totalProducts;
      int? totalQuantity;
    
      Carts(
          {this.id,
            this.products,
            this.total,
            this.discountedTotal,
            this.userId,
            this.totalProducts,
            this.totalQuantity});
    
      Carts.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        if (json['products'] != null) {
          products = <Products>[];
          json['products'].forEach((v) {
            products!.add(new Products.fromJson(v));
          });
        }
        total = json['total'];
        discountedTotal = json['discountedTotal'];
        userId = json['userId'];
        totalProducts = json['totalProducts'];
        totalQuantity = json['totalQuantity'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        if (this.products != null) {
          data['products'] = this.products!.map((v) => v.toJson()).toList();
        }
        data['total'] = this.total;
        data['discountedTotal'] = this.discountedTotal;
        data['userId'] = this.userId;
        data['totalProducts'] = this.totalProducts;
        data['totalQuantity'] = this.totalQuantity;
        return data;
      }
    }
    
    class Products {
      int? id;
      String? title;
      int? price;
      int? quantity;
      int? total;
      dynamic discountPercentage;
      int? discountedPrice;
      String? thumbnail;
    
      Products(
          {this.id,
            this.title,
            this.price,
            this.quantity,
            this.total,
            this.discountPercentage,
            this.discountedPrice,
            this.thumbnail});
    
      Products.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        title = json['title'];
        price = json['price'];
        quantity = json['quantity'];
        total = json['total'];
        discountPercentage = json['discountPercentage'];
        discountedPrice = json['discountedPrice'];
        thumbnail = json['thumbnail'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['title'] = this.title;
        data['price'] = this.price;
        data['quantity'] = this.quantity;
        data['total'] = this.total;
        data['discountPercentage'] = this.discountPercentage;
        data['discountedPrice'] = this.discountedPrice;
        data['thumbnail'] = this.thumbnail;
        return data;
      }
    }
    
    

    dio_home_screen.dart

    
    
    import 'package:b/dio_model.dart';
    import 'package:flutter/material.dart';
    import 'package:dio/dio.dart';
    
    class DioHomePage extends StatefulWidget {
      const DioHomePage({super.key});
    
      @override
      _DioHomePageState createState() => _DioHomePageState();
    }
    
    class _DioHomePageState extends State<DioHomePage> {
      // for dio
      Cart? cart;
      Future<void> getData() async {
        const String apiUrl = "https://dummyjson.com/carts";
        try {
          Response response = await Dio().get(apiUrl);
          if (response.data != null) {
            setState(() {
              cart = Cart.fromJson(response.data);
            });
          } else {
            throw Exception(" Api response is null or in an unexpected format");
          }
        } catch (e) {
          print(e.toString());
        }
      }
    
      @override
      void initState() {
        getData();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.white,
            title: const Text("Fetch Data From API Using Dio"),
          ),
          body: cart == null
              ? const Center(
            child: CircularProgressIndicator(),
          )
              : GridView.builder(
            itemCount: cart!.carts!.length,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, crossAxisSpacing: 12, mainAxisSpacing: 12),
            itemBuilder: (context, index) {
              return Material(
                borderRadius: BorderRadius.circular(20),
                elevation: 5,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.network(
                      cart!.carts![index].products![3].thumbnail ?? "",
                      height: 140,
                      width: 200,
                    ),
                    Text(
                      cart!.carts![index].products![3].title ?? "",
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 18,
                      ),
                    )
                  ],
                ),
              );
            },
          ),
        );
      }
    }
    // the reason behind type 'int' is not a subtype of type 'double?' error is
    //some api items value is both the format int and double but it dfined as one value